package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient client;

    /**
     * 文章搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {

        try {

            SearchRequest searchRequest = new SearchRequest("app_info_article");
            //布尔查询，组装多个条件
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //关键字
            if(StringUtils.isBlank(dto.getSearchWords())){
                boolQuery.must(QueryBuilders.matchAllQuery());
            }else {
                //按照字段分词之后再查询
                boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                        .field("title")
                        .field("content")
                        .defaultOperator(Operator.OR));//分词之后的词条的关系
            }

            //时间范围
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

            //把布尔查询加入条件构建器
            searchRequest.source().query(boolQuery);

            //分页
            searchRequest.source().from(0).size(dto.getPageSize());

            //时间倒序
            searchRequest.source().sort("publishTime", SortOrder.DESC);

            //高亮展示
            searchRequest.source().highlighter(new HighlightBuilder()
                    .field("title")
                    .preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>"));


            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            //结果（正常的结果+高亮结果）
            List<Map> list = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                Map map = JSON.parseObject(sourceAsString, Map.class);

                //获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(highlightFields != null && highlightFields.size() > 0){
                    HighlightField highlightField = highlightFields.get("title");
                    Text[] texts = highlightField.getFragments();
                    String h_title = StringUtils.join(texts);
                    map.put("h_title",h_title);
                }else {
                    map.put("h_title",map.get("title"));
                }

                list.add(map);

            }

            return ResponseResult.okResult(list);
        } catch (IOException e) {

            throw new RuntimeException("ArticleSearchServiceImpl-搜索失败");
        }
    }
}